<!--
  * 商品明细
  *
-->
<template>
  <div>
    <a-table :dataSource="tableData" :columns="columns" :scroll="{ x: 'max-content' }" :pagination="false" rowKey="id" size="small" bordered>
      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.dataIndex === 'purchase_total_price'"> {{ text }}</template>
        <template v-if="column.dataIndex.startsWith('20')">
          {{ record[column.dataIndex] }}
        </template>
      </template>
    </a-table>
  </div>
</template>
<script setup lang="ts">
import _ from 'lodash'
import { message } from 'ant-design-vue'
const props = defineProps({
  enterpriseId: {
    type: Array,
    default: null
  }
})

const columns = ref([
  {
    title: '商品编号',
    dataIndex: 'goods_no'
  },
  {
    title: '商品/现金',
    dataIndex: 'name'
  },
  {
    title: '规格属性',
    dataIndex: 'spec'
  },
  {
    title: '单位',
    dataIndex: 'unit'
  },
  {
    title: '条码',
    dataIndex: 'bar_code'
  },
  {
    title: '总计',
    dataIndex: 'purchase_total_price',
    width: 150
  }
])

const tableData = ref([])
const display_cycle = ref('')

const showData = (e) => {
  display_cycle.value = e.display_cycle ? e.display_cycle.split(',') : []
  tableData.value = e.detail
    ? e.detail.map((item) => {
        const rewardSet = item.reward_set || []
        const months = {}
        rewardSet.forEach((monthData) => {
          // const monthKey = Object.keys(monthData)[0]
          // months[monthKey] = monthData[monthKey]
          months[monthData.cycle_date] = monthData.cycle_num
        })
        return {
          ...item,
          ...months,
          reward_set: rewardSet // 保留原始 reward_set 数据
        }
      })
    : []
  // 计算每条记录的总计
  tableData.value.forEach((item) => {
    calculateTotal(item)
  })
  updateColumnsData()
}

// 新增月份
function updateColumnsData() {
  // 解析陈列周期的日期范围
  const displayCycle = display_cycle.value

  const startDate = new Date(displayCycle[0])
  const endDate = new Date(displayCycle[1])

  // 清空旧的月份列
  columns.value = columns.value.filter((col) => !col.dataIndex.startsWith('20'))

  // 生成新的月份列
  const newColumns = []
  let currentDate = new Date(startDate)
  while (currentDate <= endDate) {
    const monthStr = `${currentDate.getFullYear()}-${String(currentDate.getMonth() + 1).padStart(2, '0')}`
    newColumns.push({
      title: monthStr,
      dataIndex: monthStr,
      width: 150
    })
    currentDate.setMonth(currentDate.getMonth() + 1)
  }

  // 插入月份列到“总计”列之前
  const totalIndex = columns.value.findIndex((col) => col.dataIndex === 'purchase_total_price')
  columns.value.splice(totalIndex, 0, ...newColumns)
}
// 总计
function calculateTotal(record) {
  let total = 0

  // 获取陈列周期的开始日期和结束日期
  const displayCycle = display_cycle.value
  if (!displayCycle || displayCycle.length !== 2) {
    message.error('陈列周期格式不正确')
    return
  }

  const startDate = new Date(displayCycle[0])
  const endDate = new Date(displayCycle[1])

  // 生成月份数组
  const months = []
  let currentDate = new Date(startDate)
  while (currentDate <= endDate) {
    const monthStr = `${currentDate.getFullYear()}-${String(currentDate.getMonth() + 1).padStart(2, '0')}`
    months.push(monthStr)
    currentDate.setMonth(currentDate.getMonth() + 1)
  }

  // 遍历月份数组，计算总和
  months.forEach((month) => {
    if (record[month]) {
      total += record[month]
    }
  })

  record.purchase_total_price = total
}

watch(
  () => props.enterpriseId,
  (e) => {
    if (e) {
      showData(e)
    }
  },
  { immediate: true }
)
</script>

<style scoped lang="less">
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 20px 0;
}

.button-style {
  margin: 0 10px;
}
</style>
